package com.zdp.contentcenter.configuration;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author sesshomaru
 * @date 2020/9/17
 *
 * 同版本号的优先调用
 *
 */
@Slf4j
public class NacosMetadataWeightRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
    }

    @Override
    public Server choose(Object o) {
        try {
            Map<String, String> metadata = nacosDiscoveryProperties.getMetadata();
            String version = metadata.get("version");
            log.info("当前服务的版本:{}",version);

            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
            log.info("lb={}", loadBalancer);

            String name = loadBalancer.getName();
            log.info("被调用的服务实例名称:{}",name);
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
            List<Instance> instances = namingService.selectInstances(name, true);
            if (CollectionUtils.isEmpty(instances)) return null;
            // 获取到相同版本的服务实例集合
            List<Instance> sameVersionInstances = instances.stream().filter(instance -> Objects.equals(instance.getMetadata().get("version"), version))
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(sameVersionInstances)) return null;

            Instance instance = MetaExtendBalancer.getHostByRandomWeight2(sameVersionInstances);
            log.info("选择的实例是 port = {} , metadata = {}", instance.getPort(), instance.getMetadata());
            return new NacosServer(instance);

        } catch (NacosException e) {
            return null;
        }
    }
}


class MetaExtendBalancer extends Balancer {
    public static Instance getHostByRandomWeight2(List<Instance> hosts) {
        return getHostByRandomWeight(hosts);
    }
}